package com.example.security.config;

import com.example.security.dto.Role;
import com.example.security.dto.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * spring security需要的用户详情
 * <p>
 * Created by devinlee on 2021.04.25
 */
public class SecurityUserDetails implements UserDetails {
    /**
     * 系统用户
     */
    private User user;
    /**
     * 用户权限
     */
    private List<Role> roleList;

    public SecurityUserDetails(User user, List<Role> roleList) {
        this.user = user;
        this.roleList = roleList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //返回当前用户的权限
        return roleList.stream()
                .filter(o -> o.getValue() != null)
                .map(o -> new SimpleGrantedAuthority(o.getId() + ":" + o.getValue()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
